// cmd/vmctl/main.go
package main

import (
	"fmt"
	"os"

	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"

	"virt-manager-go/cmd/vmctl/commands"
	"virt-manager-go/internal/client"
)

var (
	// 全局标志
	serverURL    string
	outputFormat string
	verbose      bool

	// 全局客户端
	apiClient *client.APIClient
	logger    *logrus.Logger
)

// 提供一个获取 serverURL 的函数
func GetServerURL() string {
	return serverURL
}

func main() {
	logger = setupLogger()

	rootCmd := &cobra.Command{
		Use:   "vmctl",
		Short: "virt-manager-go command line interface",
		Long: `vmctl is a CLI tool for managing virtual machines, storage, and networks
through the virt-manager-go API server.

Examples:
  vmctl vm list                    # List all VMs
  vmctl vm start ubuntu-vm         # Start a VM
  vmctl snapshot create vm1 snap1  # Create snapshot
  vmctl batch start vm1 vm2 vm3    # Batch start VMs`,
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			apiClient = client.NewAPIClient(serverURL, logger)
		},
	}

	// 全局标志
	rootCmd.PersistentFlags().StringVarP(&serverURL, "server", "s", "http://localhost:8080", "API server URL")
	rootCmd.PersistentFlags().StringVarP(&outputFormat, "output", "o", "table", "Output format: table, json, yaml")
	rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Verbose output")

	// 添加所有子命令
	rootCmd.AddCommand(
		commands.NewConnectionCommand(logger),
		commands.NewVMCommand(logger),
		commands.NewStorageCommand(logger),
		commands.NewNetworkCommand(logger),
		commands.NewSnapshotCommand(logger),
		commands.NewMigrationCommand(logger),
		commands.NewBatchCommand(logger),
		commands.NewEventCommand(logger),
		commands.NewConsoleCommand(logger),
	)

	// 设置获取 serverURL 的函数
	commands.SetServerURLFunc(GetServerURL)

	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func setupLogger() *logrus.Logger {
	logger := logrus.New()
	logger.SetFormatter(&logrus.TextFormatter{
		DisableTimestamp: true,
	})
	logger.SetLevel(logrus.WarnLevel)
	return logger
}
